﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data;
using System.Threading;
using System.Timers;
using System.ComponentModel;
using System.Reflection;
using System.IO;

namespace TAMSUP
{
    public partial class homeWindow : Window
    {
        public static topWindow top;
        public static int efekLeft;
        public static Boolean stop;
        public static System.Timers.Timer timer;
        //public static string connectionString = "Data Source=WINDOWS-PC\\SQLEXPRESS;Initial Catalog=TAMSDB.MDF;Integrated Security=True";
        //public static string connectionString = "Data Source=XP-PC\\SQLEXPRESS;Initial Catalog=TAMSDB.MDF;Integrated Security=True";
        public static string connectionString = "Data Source=DANIELGINTING\\SQLEXPRESS;Initial Catalog=\"C:\\USERS\\DANIEL GINTING\\DOCUMENTS\\VISUAL STUDIO 2010\\PROJECTS\\BELAJARCS\\TAMSUP\\TAMSDB.MDF\";Integrated Security=True";
        public static SqlConnection Con;
        private Boolean b;

        public homeWindow()
        {
            InitializeComponent();
            initTimer();
            b = false;
        }

        private void initTimer()
        {
            timer = new System.Timers.Timer();
            timer.Elapsed += new System.Timers.ElapsedEventHandler(timerCallback);
            timer.Disposed += new EventHandler(timerDisposed);
            timer.Interval = 30;
            timer.Enabled = true;
            efekLeft = -500;
            // Start the timer
        }

        delegate void updateImage(Image img);

        private void UpdateEfekImage(Image img)
        {
            if (efekImage.Dispatcher.CheckAccess() == false)
            {
                updateImage uCallBack = new updateImage(UpdateEfekImage);
                this.Dispatcher.Invoke(uCallBack, img);
            }
            else
            {
                if (efekLeft < 799)
                    efekLeft += 3;
                else
                    efekLeft = -500;
                img.Margin = new Thickness(efekLeft, -8, 0, 0);
                if ((!stop) && (top != null) && (top.close)) Visibility = System.Windows.Visibility.Visible;
            }
        }

        public void timerCallback(object source, ElapsedEventArgs e)
        {
            if (!stop)
                UpdateEfekImage(efekImage);
        }

        public void timerDisposed(object source, EventArgs e)
        {
            efekLeft = -300;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            stop = false;
        }

        private void Window_Unloaded(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void homeWindow_Closing(object sender, CancelEventArgs e)
        {
            stop = true;
            MessageBoxResult result = MessageBox.Show("Ingin keluar dari TAMS UP?", "Exit", MessageBoxButton.YesNo);
            if (result == MessageBoxResult.Yes)
            {
                if (b)
                    top.Close();
                timer.Stop();
                timer.Dispose();
            }
            else if (result == MessageBoxResult.No)
            {
                e.Cancel = true;
                stop = false;
            }
        }

        private void helpButton_Click(object sender, RoutedEventArgs e)
        {
            try {
                System.Diagnostics.Process.Start(System.AppDomain.CurrentDomain.BaseDirectory + "\\help\\TAMSGUIDE.chm");
            } catch (Win32Exception w32e) {
                MessageBox.Show("File help tidak tersedia.\nSilakan periksa : " + System.AppDomain.CurrentDomain.BaseDirectory + "help\\TAMSGUIDE.chm");
            }
        }

        private void loginButton_Click(object sender, RoutedEventArgs e)
        {
            login();
        }

        private void usernameBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (usernameBox.Text != "")
                usernameLabel.Visibility = System.Windows.Visibility.Hidden;
            else
                usernameLabel.Visibility = System.Windows.Visibility.Visible;
        }

        private void mainProgress_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {

        }

        private void passBox_PasswordChanged(object sender, RoutedEventArgs e)
        {
            if (passBox.Password != "")
                passwordLabel.Visibility = System.Windows.Visibility.Hidden;
            else
                passwordLabel.Visibility = System.Windows.Visibility.Visible;
        }

        private void homeWindow_KeyHandle(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                login();
            }
        }

        private void login()
        {
            try
            {
                var directory = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
                var file = System.IO.Path.Combine(directory, "data\\log.tam");
                Console.WriteLine(file.ToString());
                TextReader trs = new StreamReader(file);
                connectionString = trs.ReadToEnd();
                Console.WriteLine(connectionString);
                trs.Close();

                Con = new SqlConnection(connectionString);

                Con.Open();

                SqlDataAdapter da = new SqlDataAdapter("select password,role from pengguna where username = '" + usernameBox.Text + "';", Con);
                DataSet ubah = new DataSet();
                da.Fill(ubah, "Daftar password");

                Con.Close();

                if ((ubah.Tables["Daftar password"].Rows.Count > 0) && (passBox.Password.Equals(password.DecryptString(ubah.Tables["Daftar password"].Rows[0].ItemArray.ElementAt(0).ToString()))))
                {
                    top = new topWindow();
                    b = true;
                    top.Visibility = System.Windows.Visibility.Hidden;
                    topWindow.username = usernameBox.Text;
                    topWindow.role = ubah.Tables["Daftar password"].Rows[0].ItemArray.ElementAt(1).ToString();
                    top.Visibility = System.Windows.Visibility.Visible;
                    top.Focusable = true;
                    top.FillData();
                    stop = true;
                    this.Visibility = System.Windows.Visibility.Hidden;
                    passBox.Password = "";
                }
                else
                {
                    MessageBox.Show("Username dan Password Tidak Cocok", "Error: Log In Invalid");
                }
            }
            catch (SqlException sqle)
            {
                MessageBox.Show("Ada kesalahan pada koneksi ke server, silakan periksa jaringan.\n\n SQL error code : " + sqle.State, "Error : Connection Not Established");
            }
            catch (Exception fnfe)
            {
                MessageBox.Show("Ada Kesalahan pada koneksi", "Error Connection String");
            }
        }

        private void configureButton_Click(object sender, RoutedEventArgs e)
        {
            BackUp bc = new BackUp();
            bc.Visibility = System.Windows.Visibility.Visible;
        }
    }

}
